<?php
namespace app\common;

/**
 * http请求类
 */
class HttpCurl {

    /**
     * 发送中经汇通请求
     * @param  string $url    http地址
     * @param  array $params 提交参数
     * @return string         http返回的结果
     */
    public static function zj_post($method,$params=[]){
        $url = \Yii::$app->params["zjapi"]["url"];
        $final_url = $url.$method;
        $appId = \Yii::$app->params["zjapi"]["appId"];
        $appKey = \Yii::$app->params["zjapi"]["appKey"];
        $time = time();
        $nonce = self::GetRandStr(8);
        $signature = array($appId,$appKey,$nonce,$time);
        sort($signature,2);
        $signature = implode('',$signature);
        $signature = md5($signature);
        $base_params = ['app'=>['appId'=>$appId,'timeStamp'=>$time,'nonce'=>$nonce,'signature'=>$signature]];
        $final_params = array_merge($base_params,$params);
        return self::zj_get($final_url,json_encode($final_params));
    }

    /**
     * 发送http请求
     * @param  string $url    http地址
     * @param  array $params 提交参数
     * @return string         http返回的结果
     */
    public static function zj_get($url, $params = null, $header = null, $u = null) {
        $ssl = substr($url, 0, 8) == "https://" ? TRUE : FALSE;
        $ch = curl_init();
        $opt = array(
            CURLOPT_URL             => $url,
            CURLOPT_POST            => TRUE,
            CURLOPT_POSTFIELDS      => $params,
            CURLOPT_RETURNTRANSFER  => TRUE,
            CURLOPT_TIMEOUT         => 10,
            CURLOPT_HTTPHEADER      => $header ? $header : [],
            CURLOPT_USERPWD         => $u ? $u : '',
        );
        if ($ssl)
        {
            $opt[CURLOPT_SSL_VERIFYHOST] = 2;
            $opt[CURLOPT_SSL_VERIFYPEER] = false;
        }
        curl_setopt_array($ch, $opt);
        $data = curl_exec($ch);
        if($data === false)
        {
            echo curl_error($ch);
            exit;
        }
        curl_close($ch);
        $data=json_decode($data,true);
        return $data;
    }

    public static function GetRandStr($length)
    {
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len = strlen($str) - 1;
        $randstr = '';
        for ($i = 0; $i < $length; $i++) {
            $num = mt_rand(0, $len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }


        /**
	 * 发送http请求
	 * @param  string $url    http地址
	 * @param  array $params 提交参数
	 * @return string         http返回的结果
	 */
	public static function get($url, $params = null, $header = null, $u = null)
    {
        $ssl = substr($url, 0, 8) == "https://" ? TRUE : FALSE;
        $ch = curl_init();
        $opt = array(
            CURLOPT_URL => $url,
            CURLOPT_POST => TRUE,
            CURLOPT_POSTFIELDS => $params,
            CURLOPT_RETURNTRANSFER => TRUE,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_HTTPHEADER => $header ? $header : [],
            CURLOPT_USERPWD => $u ? $u : '',
        );
        if ($ssl) {
            $opt[CURLOPT_SSL_VERIFYHOST] = 2;
            $opt[CURLOPT_SSL_VERIFYPEER] = false;
        }
        curl_setopt_array($ch, $opt);
        $data = curl_exec($ch);
        if ($data === false) {
            echo curl_error($ch);
            exit;
        }
        curl_close($ch);
        file_put_contents(date("Ymd")."_toyx.txt", $data." 日期：".date("Y-m-d H:i:s",time()).PHP_EOL,FILE_APPEND);
        //var_dump($data);
        $data = json_decode($data, true);
        if ($data['code'] == 200) {
            if(isset($data['result']))
                return $data['result'];
            else
                return true;
        } else {
            return false;
        }
    }

    public static function test_get($url, $params = null, $header = null, $u = null) {
        $ssl = substr($url, 0, 8) == "https://" ? TRUE : FALSE;
        $ch = curl_init();
        $opt = array(
            CURLOPT_URL             => $url,
            CURLOPT_POST            => TRUE,
            CURLOPT_POSTFIELDS      => $params,
            CURLOPT_RETURNTRANSFER  => TRUE,
            CURLOPT_TIMEOUT         => 10,
            CURLOPT_HTTPHEADER      => $header ? $header : [],
            CURLOPT_USERPWD         => $u ? $u : '',
        );
        if ($ssl)
        {
            $opt[CURLOPT_SSL_VERIFYHOST] = 2;
            $opt[CURLOPT_SSL_VERIFYPEER] = false;
        }
        curl_setopt_array($ch, $opt);
        $data = curl_exec($ch);
        if($data === false)
        {
            echo curl_error($ch);
            exit;
        }
        curl_close($ch);
        return $data;
    }

    public static function post($method,$params=[]){
	    $url = \Yii::$app->params["api"]["url"];
        $appKey=\Yii::$app->params["api"]['appKey'];
        $params['method'] = $method;
        $params['appKey']=$appKey;
        $params['timestamp']=date('Y-m-d H:i:s');
        $params['sign'] = self::sign($params);
        foreach ($params AS $k=>$v){
            $signparams[$k]=$k.'='.$v;
        }
        $query_string=implode('&',$signparams);
        return self::get($url,$query_string);
    }

    public static function callback_post($urlmethod,$method,$params=[]){
        $url = \Yii::$app->params["api_test_callback"]["url"].$urlmethod;
        $appKey=\Yii::$app->params["api_test_callback"]['appKey'];
        $params['method'] = $method;
        $params['appKey']=$appKey;
        $params['timestamp']=date('Y-m-d H:i:s');
        $params['sign'] = self::sign($params);
        foreach ($params AS $k=>$v){
            $signparams[$k]=$k.'='.$v;
        }
        $query_string=implode('&',$signparams);

        return self::test_get($url,$query_string);
    }

    public static function download($url, $path = 'images/'){
        if($url){
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
            $file = curl_exec($ch);
            curl_close($ch);
            $filename = pathinfo($url, PATHINFO_BASENAME);
            $resource = fopen($path . $filename, 'a');
            fwrite($resource, $file);
            fclose($resource);
            return '/'.$path . $filename;
        }else{
            return false;
        }
    }

    public static function sign($params){
        //$appKey=\Yii::$app->params["api"]['appKey'];
        $appSecret=\Yii::$app->params["api"]['appSecret'];
        //签名参数
        //$params['appKey']=$appKey;
        //$params['timestamp']=date('Y-m-d H:i:s');

        //asort($params);
        foreach($params as $k=>$v)
        {
            //去除参数名为sign和值为空的参数
            if($k==='sign'|| $v==='')
            {
                unset($params[$k]);
            }
            else
            {
                $signparams[$k]=$k.'='.$v;
            }
        }

        //对所有待签名参数按照字段名的ASCII 码从小到大排序（字典序）
        ksort($signparams);

        //重新组织所有参数的值为“key=value”

        $query_string=implode('',$signparams);

        $query_string=$appSecret.$query_string.$appSecret;


        //sha1加密
        $secret_string=strtoupper(md5($query_string));
        \Yii::info('query_string:'.$query_string.' [secret_string:'.$secret_string.']','member');
        return $secret_string;
    }

    /*public static function http($url, $method, $postfields=null, $cookie=null, $timeout=3, $headers=array()) {

        $ci = curl_init();
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_USERAGENT, 'curl'); //避免index.php >> is_mobile_request() Notice: Undefined index: HTTP_USER_AGENT
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 3);
        curl_setopt($ci, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ci, CURLOPT_ENCODING, "");

        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, 2);

        curl_setopt($ci, CURLOPT_HEADER, false);

        if ($method == 'POST')
        {
            curl_setopt ( $ci, CURLOPT_POST, TRUE );
            if (! empty ( $postfields )) {
                curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
            }
        }

        if($cookie){
            curl_setopt ( $ci, CURLOPT_COOKIE, $cookie );
        }

        curl_setopt($ci, CURLOPT_URL, $url );
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers );
        curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE );

        $response = curl_exec($ci);

        if($response === false)
        {
            echo curl_error($ci);
            exit;
        }
        curl_close ($ci);

        return $response;
    }*/

}